package com.loiane.dataaccess;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.loiane.exception.CheckURLException;
import com.loiane.model.TransformerItem;
import com.loiane.model.URLCheckingResult;
import com.loiane.service.CheckURLService;

public class CheckURLDatabaseAccessor extends BaseDataBaseAccessor implements CheckURLService{

	private static final String GET_AVAI_URL = " SELECT ID,NAME FROM URLS WHERE ISAVAILABLE = ?";
	@Override
	public List<TransformerItem> getURLs(int isavailable) throws CheckURLException{
		Connection conn = this.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		List<TransformerItem> items = new ArrayList<TransformerItem>();
		TransformerItem tf = null;
		try {
			ps = conn.prepareStatement(GET_AVAI_URL);
			ps.setInt(1, isavailable);
			rs = ps.executeQuery();		
			while(rs.next()){
				tf = new TransformerItem();
				tf.setId(rs.getInt(1));
				tf.setName(rs.getString(2));
				items.add(tf);
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw new CheckURLException();
		}finally{
			if(conn != null){
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		return items;
	}
	@Override
	public List<URLCheckingResult> checkURLs() throws CheckURLException {
		List<TransformerItem> urls = this.getURLs(1);
		List<URLCheckingResult> results = new ArrayList<URLCheckingResult>();
		TransformerItem ti = null;
		URLCheckingResult ur = null;
		int count = urls.size();
		
		for(int i = 0; i < count; i++){
			ti = urls.get(i);
			ur = new URLCheckingResult();
			HttpURLConnection conn = null;

			try {
				String resUrl = ti.getName();
				URL url;
				url = new URL(resUrl);
				
				int result = 0;
				conn = (HttpURLConnection) url.openConnection();
				result = conn.getResponseCode();
				if (result != HttpURLConnection.HTTP_OK) {
					System.err.println("Connect failed!! ");
					ur.setUrl(ti.getName());
					ur.setAvailable(false);
				}else{
					System.out.println("Connect success!! ");
					ur.setUrl(ti.getName());
					ur.setAvailable(true);
				}		
				results.add(ur);
				conn.disconnect();
			} catch (MalformedURLException e) {
				e.printStackTrace();
				ur.setUrl(ti.getName());
				ur.setAvailable(false);
				results.add(ur);
			} catch (IOException e) {
				e.printStackTrace();
				ur.setUrl(ti.getName());
				ur.setAvailable(false);
				results.add(ur);
			} finally{
				conn.disconnect();
			}
		}
		System.out.println("result: " + results);
		return results;
	}
}
